<template>
  <div class="notificationManagementList">
    <el-card>
      <el-button
        @click="dialogFormVisible = true"
        class="btn"
        >添加系统消息</el-button
      >
      <el-table :data="tableData"  style="width: 100%">
        <el-table-column prop="id" label="消息ID"> </el-table-column>
        <el-table-column prop="creationTime" label="创建时间">
        </el-table-column>
        <el-table-column prop="title" label="标题"> </el-table-column>
        <el-table-column prop="content" label="内容"> </el-table-column>
        <el-table-column prop="launch" label="投放">
          <template slot-scope="scope">
            <span>{{ scope.row.launch == 1 ? "男用户" : "女用户" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="publisher" label="发布者"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="withdrawBtn(scope.row)"
              type="danger"
              v-if="scope.row.state == 0"
              >撤回</el-button
            >
            <span v-if="scope.row.state == 1">已撤回</span>
            <!-- <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="scope.row.state == 0"
              >已撤回</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      />

      <el-dialog
        title="系统消息发布"
        :visible.sync="dialogFormVisible"
        top="5vh"
      >
        <el-form :model="form">
          <el-form-item label="标题" :rules="[{ required: true }]">
            <el-input v-model="form.title" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="内容">
            <el-input type="textarea" v-model="form.content"></el-input>
          </el-form-item>
          <el-form-item label="投放用户" :rules="[{ required: true }]">
            <el-checkbox-group v-model="form.launchUsers">
              <el-checkbox label="1" name="">男用户</el-checkbox>
              <el-checkbox label="2" name="">女用户</el-checkbox>
              <el-checkbox label="3" name="">VIP用户</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="推送时间" :rules="[{ required: true }]">
            <el-radio-group v-model="pushTime">
              <el-radio label="立即发送"></el-radio>
              <el-radio label="定时发送"></el-radio>
            </el-radio-group>

            <el-date-picker
              v-model="form.pushTime"
              type="datetime"
               value-format="timestamp"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="添加图片" :rules="[{ required: true }]">
            <el-upload
              class="avatar-uploader"
              :http-request="upLoad"
              :on-preview="handlePictureCardPreview"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              action
            >
              <img
                v-if="dialogImageUrl"
                :src="dialogImageUrl"
                class="avatar"
                style="width: 200px; height: 180px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="添加链接" :rules="[{ required: true }]">
            <el-input placeholder="请输入内容" v-model="form.url">
              <template slot="prepend">Http://</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="noticeAddBtn">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  noticeList,
  noticeDel,
  ossToken,
  noticeAdd,
} from "@/api/NotificationManagement";
import Pagination from "@/components/Pagination"; // 分页
import { client } from "@/utils/oss.js";

export default {
  components: { Pagination },
  inject: ["reload"],
  data() {
    return {
      input1: "",
      tableData: [],
      dialogFormVisible: false,
      form: {
        title: "",
        content: "",
        launchUsers: [],
        pushTime: "",
        imageUrl: "",
        url: "",
      },
      pushTime: "",
      total: 0,
      page: 1, //页码
      pageSize: 10, //每页条数
      dialogImageUrl: "",
    };
  },
  methods: {
    //列表
    noticeList() {
      noticeList({
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = res.data.count;
        }
      });
    },
    //分页
    getList() {
      noticeList({
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = res.data.count;
        }
      });
    },
    //撤回
    withdrawBtn(row) {
      this.$confirm("此操作将撤回该系统消息, 是否继续?", "撤回提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          noticeDel({
            id: row.id,
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "撤回成功",
              });
              this.reload();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消撤回",
          });
        });
    },
    //添加系统消息
    noticeAddBtn() {
      this.dialogFormVisible = true;
      console.log(this.form);
      noticeAdd({
        title: this.form.title, //标题
        content: this.form.content, //内容
        launchUsers: this.form.launchUsers, //投放 1.男用户 2.女用户
        pushTime: this.form.pushTime, //推送时间
        img: this.form.imageUrl, //添加图片
        url: this.form.url, //添加链接
      }).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: "添加成功",
          });
          this.reload();
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        // fileNames = "/img/" + file.file.name;
        fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      this.form.imageUrl = fileNames;
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          //下面是如果对返回结果再进行处理，根据项目需要
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
  },
  created() {
    this.noticeList();
  },
};
</script>

<style lang="less" >
.notificationManagementList {
  margin: 30px;
  height: 100%;
  .el-table {
    margin-top: 20px;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    margin-left: 20px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>